package org.example;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音工具类
 *
 * @author 高旭
 */
public class PinYinUtil {

    /**
     * 将汉字转换为全拼
     *
     * @param src
     * @return
     */
    public static String getPinYin(String src) {
        StringBuilder pinYinStr = new StringBuilder(16);

        /*设置汉子拼音输出的格式*/
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        char[] hz = src.toCharArray();
        try {
            for (char c : hz) {
                //先判断是否为汉字字符
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    //将汉字的几种全拼都存到py数组中
                    String[] py = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    //取出改汉字全拼的第一种读音，并存放到字符串pys后
                    pinYinStr.append(py[0]);
                } else {
                    //如果不是汉字字符，间接取出字符并连接到 pys 后
                    pinYinStr.append(c);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return pinYinStr.toString();
    }

    /**
     * 测试
     */
    public static void main(String[] args) {
        String str = "1中国梦ChainDream2018";
        System.out.println(getPinYin(str));
    }

}
